﻿using System;
using System.ComponentModel;
using System.Linq;
using AppLimit.CloudComputing.SharpBox;
using UploadClient.Interfaces;
using UploadClient.Interfaces.Upload;

namespace DropBoxUploadPlugin
{
    class Upload : BackgroundWorker
    {
        static BackgroundWorker bw;
        static UserState userState = new UserState();
        static string currentFile;


        //DropBoxCredentials dropBoxCredentials = new DropBoxCredentials();
        readonly CloudStorage dropBoxStorage = new CloudStorage();
        ICloudStorageConfiguration dropBoxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);

        /// <summary>
        /// Adds the DoWork-Event internal.
        /// </summary>
        public Upload()
        {
            this.DoWork += new DoWorkEventHandler(Upload_DoWork);
        }

        public IUploadHost Host { private get; set; }

        /// <summary>
        /// The work that runs in the background thread.
        /// <remarks>This methode uses the username and pw from the first UploadItem to connect to the server.</remarks>
        /// </summary>
        /// <param name="sender">BackgroundWorker.</param>
        /// <param name="e">e.Argument from type UploadItem[].</param>
        //[System.Diagnostics.DebuggerNonUserCode()]
        private void Upload_DoWork(object sender, DoWorkEventArgs e)
        {
            // params
            bw = sender as BackgroundWorker;
            UploadItem[] uploadItems = e.Argument as UploadItem[];
            
            userState.GetFinishedFilesCount = 0;
            userState.GetRemainingQueCount = 0;
            userState.Message = string.Empty;

            IServerSettings settings = uploadItems[0].ServerSettings as IServerSettings;
            int finishedFiles = -1;

            // ToDo: keep it secret!?!
            //dropBoxCredentials.ConsumerKey = "key";
            //dropBoxCredentials.ConsumerSecret = "secret";
            //dropBoxCredentials.UserName = settings.Username;
            //dropBoxCredentials.Password = settings.Password;

            userState.GetFinishedFilesCount = 0;
            userState.GetRemainingQueCount = uploadItems.Count();
            userState.Message = Host.GetLocalizationRessourceString("Connecting to DropBox..");
            bw.ReportProgress(0, userState);

            // Get connection token from dropbox
            //ICloudStorageAccessToken storageToken = dropBoxStorage.Open(dropBoxConfig, dropBoxCredentials);

            foreach (UploadItem item in uploadItems)
            {
                finishedFiles++;

                userState.GetRemainingQueCount = uploadItems.Count() - finishedFiles;
                userState.GetFinishedFilesCount = finishedFiles;
                userState.Message = string.Format(Host.GetLocalizationRessourceString("Uploading file: {0}"), item.Filename);
                bw.ReportProgress(0, userState);

                if (bw.CancellationPending) { e.Cancel = true; return; }

                currentFile = item.Filename;
                dropBoxStorage.UploadFile(item.Filepath, item.ServerSettings.Dir, UploadDownloadProgress);
            }
            dropBoxStorage.Close();
        }


        private static void UploadDownloadProgress(Object sender, FileDataTransferEventArgs e)
        {
            userState.Message = String.Format("{0} - Transferred {1} / {2}", currentFile, e.CurrentBytes, e.TotalBytes);
            bw.ReportProgress(e.PercentageProgress, userState);
            
            if(bw.CancellationPending) e.Cancel = true;
        }

        #region Nested type: FileOperationProgressChanged

        delegate void FileOperationProgressChanged(object sender, FileDataTransferEventArgs e);

        #endregion
    }
}
